<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        :rules="rules"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker
            v-model="queryForm.beginDate"
            style="width: 150px;"
            type="date"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="queryForm.endDate"
            style="width: 150px;"
            type="date"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <my-area-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <ve-line :data="chartData" :settings="chartSetting"></ve-line>
      </template>
    </split-pane>
  </d2-container>
</template>

<script>
import MyAreaTree from "@/components/my-area-tree";
import dayjs from "dayjs";
import VeLine from "v-charts/lib/line";

export default {
  name: "trend",
  components: { MyAreaTree, VeLine },
  data() {
    return {
      queryForm: {
        areaId: "1",
        beginDate: dayjs().format("YYYY-MM-DD"),
        endDate: dayjs()
          .add(7, "day")
          .format("YYYY-MM-DD")
      },
      rules: {
        beginDate: [{ required: true, message: "必填", trigger: "blur" }],
        endDate: [{ required: true, message: "必填", trigger: "blur" }]
      },
      loading: false,
      chartData: null,
      chartSetting: {
        labelMap: {
          datetime: "时间",
          value: "用量"
        }
      }
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.fetchData();
    },
    handleFormSubmit() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          this.fetchData();
        } else {
          return false;
        }
      });
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_loopRatio_getTrendStatisticsChartVO({
          ...this.queryForm
        })
        .then(res => {
          this.chartData = {
            columns: ["datetime", "value"],
            rows: res
          };
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
